import { Get, Injectable, Param, ParseUUIDPipe } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './user.entity';
import { DeleteResult, EntityManager, getManager, Repository } from 'typeorm';
import { UserExtend } from '../userExtend/userExtend.entity';
import { CreateUserExtendDto } from '../userExtend/userExtend.dto';
import { Role } from '../role/role.entity';
import { CreateUserDto } from './dto/create.user.dto';
import { AddRoleDto } from './dto/add.role.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Role)
    private readonly roleRepository: Repository<Role>,
  ) {
  }

  // 创建数据,传递一个对象类型的数据
  async create(data: Extract<CreateUserDto, CreateUserExtendDto>, manager: EntityManager) {
    const { username, password, address, mobile } = data;
    const user: { [propName: string]: any } = await manager.save(manager.create(User,{
      username,
      password,
    }));
    await manager.save(UserExtend, {
      user: user,
      mobile,
      address,
    });
    return '创建成功';
  }

  // 查询全部的数据
  async userList(): Promise<User[]> {
    return await this.userRepository.find({ relations: ['userDetail', 'posts', 'roles'] });
  }

  // 删除数据
  async delete(id): Promise<DeleteResult> {
    return await this.userRepository.delete(id);
  }

  // 添加角色
  async addRole({ userIds, roleIds }: AddRoleDto) {
    console.log(userIds, roleIds);
    const roles = await this.roleRepository.findByIds(roleIds.split(','));
    console.log(roles);
    let users = await this.userRepository.findByIds(userIds.split(','));
    console.log(users);
    if (roles.length && users.length) {
      users = users.map(user => {
        user.roles = roles;
        return user;
      });
      console.log('users', users);
      await this.userRepository.save(users);
      // await this.roleRepository.save(roles);
    }
    return '添加成功';
  }

  async validLogin({ username, password }: User) {
    const find = await this.userRepository.findOne({ where: [{ username }, { password }] });
    return find;
  }

}
